<template>
  <div>
  <div class="article_all" v-show="!editorVis">
    <div class="article_head">
      <div class="article_head_left">
        <el-button class="addArticle" icon="el-icon-plus" @click="toAddArticle">新增文章</el-button>
        <el-input placeholder="搜索" v-model.trim="searchInput" @change="searchArticle" clearable></el-input>
      </div>
      <div class="article_head_right" v-show="showControls">
        <el-button style="border-radius: 10px;" @click="dialogRoleVisible = true;">修改权限</el-button>
        <el-button type="danger" style="border-radius: 10px;" @click="deleteSelect">删除选中</el-button>
      </div>
    </div>
    <div style="width: 100%;">
    <div class="article_body">
      <el-table ref="articleTableRef" :data="selectedItems" height="460px" style="margin-top: 16px;font-size: 14px;" @selection-change="handleSelectionChange"
        :header-cell-style="{ background: '#EBEEF2' }" :row-style="{ height: '80px' }">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="articleName" label="文章标题" min-width="150"></el-table-column>
        <el-table-column prop="categoryNames" label="分类" min-width="120"></el-table-column>
        <el-table-column prop="publicTime" label="发布时间" min-width="120" sortable>
          <template slot-scope="scope">
            {{ scope.row.onlineState?scope.row.publicTime:'未发布' }}
          </template>
        </el-table-column>
        <el-table-column label="浏览权限" min-width="70" align="center">
          <template slot-scope="scope">{{ scope.row.permType==0?'默认':'自定义' }}</template>
        </el-table-column>
        <el-table-column prop="htmlPath" label="链接" min-width="80">
          <template slot-scope="scope" :title="scope.row.link">
            <el-button size="mini" style="border-radius: 10px;" @click="copyLink(scope.row.htmlPath)">复制</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="viewCount" label="浏览数">
          <template slot-scope="scope">
            {{ scope.row.visitCount?scope.row.visitCount:0 }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200px">
            <template slot-scope="scope">
              <div style="display: flex;align-items: center;" @click="control(scope.row,scope.$index)">
                <el-image class="control_button" data-control="check" :src="require('../../assets/article/check.png')"></el-image>
                <el-image class="control_button" data-control="edit" :src="require('../../assets/article/edit.png')"></el-image>
                <el-image v-if="scope.row.onlineState===0" class="control_button" data-control="public" :src="require('../../assets/article/public.svg')"></el-image>
                <el-image class="control_button" data-control="delete" :src="require('../../assets/article/throw.png')"></el-image>
              </div>
            </template>
          </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination :current-page.sync="currentPage" :page-size.sync="pageSize"
      :page-sizes="[5, 10, 20, 50 ,100]" layout="prev, pager, next, sizes , total" :total="total"
      background style="margin-top: 10px;" @size-change="getArticleList"
      @current-change="getArticleList"/>
    </div>
  </div>
  <div class="loading" v-load:[loadText]="loading" />
  <!-- <AddCommodity :dialogType="dialogType" :form="form" :dialogVisible.sync="dialogVisible" @submit="submit" @toEditor="dialogVisible=false;editorVis=true;"/> -->
  <AddCommodity :dialogType="dialogType" :form="form" :dialogVisible.sync="dialogVisible" @submit="submit" @toEditor="dialogVisible=false;"/>
  </div>
  <!-- <CreateNewArticle :form="form" v-if="editorVis" @goBack="dialogVisible=true;editorVis=false;"/> -->
  <el-dialog top="15%" width="500px" title="修改权限" :visible.sync="dialogRoleVisible">
    <el-form style="height: 20px;font-size: larger;">
      <el-form-item label="浏览权限：" style="display: flex;align-items: center;">
        <el-radio-group v-model="role">
          <el-radio :label="0">默认</el-radio>
          <el-radio :label="1">自定义</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogRoleVisible = false">取 消</el-button>
      <el-button type="primary" @click="editRoleSelect">确 定</el-button>
    </div>
  </el-dialog>
</div>
</template>

<script>
import AddCommodity from './components/AddCommodity.vue';
import { getArticleList,deleteArticle,viewArticleDetail,addArticle,
  updateOnlineStatus,editArticle, getFolderId, fileUpload, generateArticle } from "@/api/api.js";
import CreateNewArticle from './createNewArticle/index.vue';
export default {
  name: 'Laucher',
  components:{AddCommodity,CreateNewArticle},
  data() {
    return {
      searchInput:'',
      loadText:'加载中···',
      loading:false,
      dialogType:'新增',
      dialogRoleVisible:false,//权限修改弹窗显示
      selectedItems:[
        {title: '海湾专业规模型风电场拟于年底启动建设', type: '资讯中心 -企业资讯', publicTime: '2017-09-30 11:46', viewPermission: '默认', link: 'www.i3vsoft.com', viewCount: 1254},
        {title: '海湾专业规模型风电场拟于年底启动建设拟于年底...', type: '产品中心-BIM辅助设计-海洋工程', publicTime: '2017-09-30 11:46', viewPermission: '默认', link: 'www.i3vsoft.com', viewCount: 8},
        {title: '海湾专业', type: '行业动态', publicTime: '2017-09-30 11:46', viewPermission: '默认', link: 'http://www.baidu.com', viewCount: 634},
      ],
      multipleSelection:[],//多选项
      showControls:false,//多选按钮显示
      dialogVisible:false,//新增文章弹窗显示
      editorVis:false,//编辑文章页显示
      currentPage:1,//当前页数
      pageSize:5,//每页显示条数
      total:10,//总数
      role: 0,//修改权限
      curDate:{},//当前新增文章暂存数据
      form:{
        articleName: "", //标题
        detailContent: "", //详细内容
        delFlag:0, //删除标记
        author:'', //作者
        permType:0, //权限
        src:'', //来源
        introduce:'', //介绍-暂无-暂存发布地址
        categoryId:'' ,//分类
        articleAbstract:'', //文章摘要
        // articleId:'', //文章ID
        coverPath:''//封面
      },
    }
  },
  async created() {
    await this.getArticleList();
  },
  beforeRouteEnter(to, from, next) {
    next(async (vm) => {
      if(from.fullPath === '/Main/articleManage/editor'){
        const change = vm.$store.getters.getArticleChange;
        if(change != null){
          vm.form.detailContent = vm.$store.getters.getArticleHTML;
          vm.form.change = true;
        }
        vm.dialogVisible = true;
      }else if(from.fullPath === '/Main/articleManage/createModel')
        vm.dialogVisible = true;
      else await vm.getArticleList();
    });
  },
  methods:{
    // 多选框
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 复制链接
    copyLink(link){
      if(link == null||link == ''){ this.$message({message: '链接为空',type: 'warning'});return;}
      var aux = document.createElement("input"); 
      aux.setAttribute("value", link); 
      document.body.appendChild(aux); 
      aux.select();
      document.execCommand("copy"); 
      document.body.removeChild(aux);
      this.$message({message: '复制成功',type: 'success'});
    },
    
    // 操作
    control(row,index){
      switch(event.target.dataset.control){
        case 'check':
          if(row.onlineState){
            window.open(row.htmlPath);
            generateArticle(row.id).then(resp => {
              if(resp.data.code != 200) this.$message.error('预览统计失败！');
              else row.visitCount++;
            }).catch(err => {this.$message.error('预览统计失败！');});
          }else this.$message.warning('文章未发布，无法预览');
          break;
        case 'edit':
          if(this.dialogType === '新增'){
            this.curDate = structuredClone(this.form);
            this.dialogType = '编辑';
          }
          this.form = row;
          this.form.articleId = row.id;
          this.dialogVisible = true;
          break;
        case 'public':
          this.$confirm(`是否确认发布[${row.articleName}]?`, '发布', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              confirmButtonClass: 'btnTrues',
              type: 'warning'
            }).then(() => {
              this.toPublic(row);
            }).catch(() => {})
          break;
        case 'delete':
          this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            confirmButtonClass: 'btnTrues',
            type: 'warning'
          }).then(() => {
            deleteArticle(row.id).then( async(resp) => {
              if(resp.data.code == 200){
                if(this.currentPage>1&&index===0) this.currentPage--;
                this.getArticleList();
                this.$message({type: 'success',message: '删除成功!'});
              }else{ this.$message({type: 'error',message: '删除失败!'});}
            }).catch((e)=>{this.$message({type: 'error',message: '处理失败!'});})
          }).catch(() => {})
          break;
      }
    },

    // 文章发布
    async toPublic(row){
      try{
        this.loading = true;
        const blob = new Blob([row.detailContent], {'type': 'text/html'});
        const file = new File([blob], 'article.html');
        const href = await this.uploadFile(file);
        if(href == null) throw new Error('上传失败');
        await editArticle({articleId:row.id,introduce:href}).then(resp => {
          if(resp.data.code != 200)
            this.$message.error('文章html上传失败！')
        }).catch(e => {this.$message.error('处理失败！')})
        await updateOnlineStatus({articleId:row.id,onlineState:1}).then( async(resp) => {
          if(resp.data.code == 200){
            this.getArticleList();
            this.$message({type: 'success',message: '文章发布成功!'});
          }else{ this.$message({type: 'error',message: '文章发布失败!'});}
        }).catch((e)=>{this.$message({type: 'error',message: '处理失败!'});})
      }catch(e){
        this.$message({type: 'error',message: '处理失败!'});
      }finally{this.loading = false;}
    },

    // 新增文章
    toAddArticle(){
      if(this.dialogType === '编辑'){
        this.form = structuredClone(this.curDate);
        this.dialogType='新增';
      }
      this.dialogVisible=true;
    },

    // 批量删除
    deleteSelect(){
      if(this.multipleSelection.length === 0){ this.$message({type: 'warning',message: '未选择删除项!'}); return;}
      const ids = this.multipleSelection.map(item => item.id);
      this.$confirm(`此操作将永久删除选中的文章, 是否继续?`, '提示', {
        confirmButtonText: '确定',    
        cancelButtonText: '取消',
        confirmButtonClass: 'btnTrues',
        type: 'warning'
      }).then(() => {
        deleteArticle(ids.join(',')).then(async(resp)=>{
          if(resp.data.code == 200){
            const iindex = (this.total-this.multipleSelection.length)/this.pageSize;
            if(this.currentPage>iindex) this.currentPage = iindex;
            await this.getArticleList();
            this.$message({type: 'success',message: '删除成功!'});
          }else this.$message({type: 'error',message: '删除失败!'});
        })
      }).catch(() => {})
    },

    // 修改权限
    async editRoleSelect(){
      for(let i=0;i<this.multipleSelection.length;i++){
        await editArticle({articleId:this.multipleSelection[i].id,permType:this.role}).then(resp => {
            if(resp.data.code != 200)
              this.$message.error('文章浏览权限修改失败！')
          }).catch(e => {this.$message.error('处理失败！')})
      }
      this.getArticleList();
      this.dialogRoleVisible = false;
      this.$refs.articleTableRef.clearSelection();
      this.multipleSelection = [];
      this.$message.success('文章浏览权限修改成功！');
    },

    // 获取文章列表
    async getArticleList(){
      try{
        this.loading = true;
        const list = await getArticleList({
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          articleName:this.searchInput,
          sort: "updateAt",
          sortType: "desc"
        });
        if(list.data.code == 200){
          // 下面这里后面要改
          this.selectedItems = list.data.result?.records.map(element => {
            if(element.onlineState){
              // const blob = new Blob([element.detailContent], {'type': 'text/html'});
              // return { ...element, htmlPath: URL.createObjectURL(blob) };
              return { ...element, htmlPath: element.introduce+'?download=0' };
            }
            else return element;
          });
          this.total = list.data.result?.total;
        }else{
          this.$message({message: '文章列表获取失败！',type: 'error'});
        }
      }catch(e){
        this.$message({message: '处理失败！',type: 'error'});
        console.log(e)  
      }finally{
        this.loading = false;
      }
    },

    // 搜索文章
    async searchArticle(){
      this.currentPage = 1;
      await this.getArticleList();
    },

    // 新增文章
    async submit(){
      try{
        const { articleName, detailContent, src, author, categoryId, coverPath } = this.form;
        this.loading = true;
        // 封面图片上传
        if(coverPath&& coverPath.url){
          this.form.coverPath = await this.uploadFile(coverPath.raw);
        }
        // 文章上传html更新
        if(this.form.onlineState&&this.form.change){
          const blob = new Blob([this.form.detailContent], {'type': 'text/html'});
          const file = new File([blob], 'article.html');
          const href = await this.uploadFile(file);
          if(href == null) throw new Error('上传失败');
          this.form.introduce = href;
        }
        // 新增
        if(articleName && src && author && categoryId && coverPath){
          if(this.dialogType === '新增'){
            await addArticle(this.form).then(resp => {
              if(resp.data.code == 200){
                this.getArticleList();
                this.reflash();
                this.$message.success('文章添加成功！');
                this.dialogVisible = false;
              }else{this.$message.error(resp.data.message)}
            }).catch(e => {this.$message.error('处理失败！')})
          }else{
            await editArticle(this.form).then(resp => {
              if(resp.data.code == 200){
                this.getArticleList();
                this.reflash();
                this.$message.success('文章编辑成功！');
                this.dialogVisible = false;
              }else{this.$message.error('文章编辑失败！')}
            }).catch(e => {this.$message.error('处理失败！')})
          }
        }else{this.$message.error('请完善文章信息！')}
        }catch(e){
          this.$message.error('处理失败！');
        }finally{
          this.loading = false;
        }
    },

    // 上传文件
    async uploadFile(file){
      const folderId = await this.getFolderId();
      const formData = new FormData();
      formData.append('file',file);
      formData.append('folderId',folderId);
      // formData.append('id','ff80808191c5f1790191c60879980007');
      formData.append('isCover','0');
      return await fileUpload(formData).then(resp => {
        if(resp.data.code == 200){
          return resp.data.result.src;
        }else{this.$message.error('文件上传失败！')}
      }).catch(e => {this.$message.error('处理失败！')})
    },

    // 获取文件夹id
    async getFolderId(){
      return await getFolderId({
        folderName: "官网",
        folderDescribe: "官网目录自动创建",
        folderAttributes: '{"dataType":0}',
      }).then(resp => {
        if(resp.data.code == 200){
          return resp.data.result;
        }else{this.$message.error('文件夹路径获取失败！')}
      }).catch(e => {this.$message.error('处理失败！')})
    },

    // 刷新
    reflash(){
      this.form={
        articleName: "", //标题
        detailContent: "", //详细内容
        delFlag:0, //删除标记
        author:'', //作者
        permType:0, //权限
        src:'', //来源
        introduce:'', //介绍-暂无
        categoryId:'' ,//分类
        articleAbstract:'', //文章摘要
        // articleId:'', //文章ID
        coverPath:''//封面
      };
      this.curDate = {};
    }
  },
  computed:{
    // searchDate(){
      // 这里之后对接后端
      // return this.selectedItems.filter(item => item.title.includes(this.searchInput));
    //   return this.selectedItems;
    // }
  },
  watch:{
    multipleSelection(nl,ol){
      if(this.multipleSelection.length > 0)
        this.showControls = true;
      else
        this.showControls = false;
    },
  }
}

</script>

<style scoped>
.article_head{
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}
.addArticle {
  background-color: #7e72f2;
  color: white;
  border-radius: 10px;
  margin-right: 10px;
}
.addArticle:hover{
  color: #ebeafc;
}
.article_head_left,.article_head_right{
  display: flex;
  align-items: center;
}
.article_head_right{
  flex-wrap: wrap;
}
.article_head_left ::v-deep .el-input--suffix .el-input__inner{
  border-radius: 10px;
  box-shadow: 0 0 1px #7e72f2;
}
.control_button{
  min-width: 20px;
  min-height: 20px;
  max-width: 20px;
  max-height: 20px;
  margin-right: 20px;
  cursor: pointer;
  filter: drop-shadow(#FFFFFF 0 0);
}
.control_button:hover{
  filter: drop-shadow(0 0 0 #0015ff);
}
.pagination ::v-deep .el-pagination .el-pager .number.active{
  background-color:#456ddc !important;
  border-color: #456ddc !important;
  color: white !important;
}
.pagination ::v-deep .el-pagination .el-pager .number{
  color: #456ddc !important;
}
.pagination ::v-deep .el-pagination{
  position:relative;
}
.pagination{
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: right;
}
::v-deep .el-checkbox__input.is-checked .el-checkbox__inner{
  background-color: #456ddc;
  border-color:#456ddc;
}
::v-deep .el-checkbox__input.is-indeterminate .el-checkbox__inner{
  background-color: #456ddc;
  border-color:#456ddc;
}
::v-deep .el-checkbox__inner:hover{
  border-color:#456ddc;
}
.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
}
</style>